<template>
  <BasicDrawer v-bind="$attrs" :isDetail="true" @register="register">
    <!-- <p class="h-20">Content Message</p> -->
    <Row :gutter="[20, 20]">
      <Col :xl="6" :lg="24">
      <Card title="设备位置信息" hoverable>
        <BasicForm @register="registerForm">
        </BasicForm>
        <!-- <button @click="zoomIn">放大</button>
        <button @click="zoomOut">缩小</button> -->
      </Card>
      </Col>
      <Col :xl="18" :lg="24">
      <Card class="rightcard" id='rightcard' hoverable :bodyStyle="{ padding: '0px' }">
        <div class="image-annotation" id="imgcanvas" ref="imagcanvasref">
          <!-- <img id="senceurl" alt="" class="box" :src="currentIMG" /> -->
          <canvas ref="canvas" @click="handleClick"></canvas>
        </div>
      </Card>
      </Col>
    </Row>
    <template #titleToolbar>
      <a-button type="primary" class="my-4" @click="handleSubmit">提交</a-button>
    </template>
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { BasicDrawer, useDrawerInner } from '@/components/Drawer'
import { Card, Row, Col, Input } from 'ant-design-vue';
import { BasicForm, FormSchema, useForm } from '@/components/Form';
import { getScenceList } from '@/api/collection/scence/index';
import { onMounted, ref, reactive, h, onUnmounted } from 'vue';
import { getOrganizationTree } from '@/api/sys/dept';
import { fileDownload } from '@/api/download/index';
import defaultScence from '@/assets/images/defaultSence.svg'
import location from '@/assets/images/location.svg'
import { updateDevice } from '@/api/collection/device';

// 获取canvas元素
const canvas = ref<HTMLCanvasElement>();
const imagcanvasref = ref<HTMLCanvasElement>();
// const points = reactive([]);
const currentIMG = ref(defaultScence);
let originWH = reactive({ width: 0, height: 0 });
// 定义保存图标坐标的状态
const iconPosition = ref<{ x: any; y: any }>({ x: 0, y: 0 });
// const imageSize = ref<{ width: any; height: any }>();
// 定义图标的Image对象
const iconImage = ref<HTMLImageElement>(new Image());
const recordRef = ref();
const currentSenceId = ref();
const emit = defineEmits(['success']);
const locationSchemas: FormSchema[] = [
  {
    field: 'building',
    component: 'ApiSelect',
    label: '楼栋',
    required: true,
    colProps: {
      span: 24,
    },
    componentProps: ({ formModel, formActionType }) => {
      return {
        api: getScenceList,
        labelField: 'name',
        valueField: 'id',
        immediate: true,
        onChange: async (e, v) => {
          // console.log('ApiSelect====>:', e, v);
          if (typeof (e) === "string") {
            const ret = await getScenceList(e)
            const floorOptions = ret.map(item => ({
              value: item.id,
              label: item.name,
              key: item.file?.id,
              frame: item.frame,
            }))
            // formModel.floor = undefined; //  reset floor value
            const { updateSchema } = formActionType;
            updateSchema({
              field: 'floor',
              componentProps: {
                options: floorOptions,
              },
            });
          }
        },
      };
    },
  },
  {
    field: 'floor',
    component: 'Select',
    label: '楼层',
    colProps: {
      span: 24,
    },
    componentProps: {
      options: [],
      onChange: async (e, v) => {
        // console.log('ApiChildrenSelect====>:', e, v);
        currentSenceId.value = e;
        v && reloadIMG(v.key, false, v)
      }
    },
  },
  {
    field: 'orgId',
    component: 'ApiTreeSelect',
    label: '责任部门',
    required: true,
    colProps: {
      span: 24,
    },
    componentProps: {
      api: getOrganizationTree,
      labelField: 'name',
      valueField: 'id',
      onChange: (e, ...v) => {
        // console.log('ApiSelect====>:', e, v);
      },
    },
  },
  {
    field: 'x',
    component: 'Input',
    label: 'X轴坐标',
    dynamicDisabled: true,
  },
  {
    field: 'y',
    component: 'Input',
    label: 'Y轴坐标',
    dynamicDisabled: true,
  }
];

const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
  layout: "vertical",
  baseColProps: { span: 24 },
  schemas: locationSchemas,
  showActionButtonGroup: false,
  autoFocusFirstItem: true
})

const [register, { closeDrawer }] = useDrawerInner(async (record) => {
  recordRef.value = record;

  // 初始化图片
  if (record.data.floor) {
    const ret = await getScenceList(record.data.floor?.parentId)
    if (ret && ret[0]) {
      reloadIMG(ret[0]?.file?.id, true, ret[0])
    }
  }

  // 重置
  setFieldsValue({
    building: record.data?.building?.id || undefined,
    floor: record.data?.floor?.id || undefined,
    x: record.data.coordinate?.x || 0,
    y: record.data.coordinate?.y || 0,
    orgId: record.data?.org?.orgId || undefined,
  });

  iconPosition.value = {
    x: record.data.coordinate?.x,
    y: record.data.coordinate?.y
  }

});

/**
 * 在图片上点击时，更新icon
 */
const handleClick = (event: MouseEvent) => {
  if (!canvas.value || !canvas.value.getContext) return;

  console.log('handleclick...', imagcanvasref.value.clientHeight, imagcanvasref.value.clientWidth);

  // 计算点击位置
  const rect = canvas.value?.getBoundingClientRect();
  const x = event.clientX - rect.left;
  const y = event.clientY - rect.top;

  const xScale = x / imagcanvasref.value.clientWidth;
  const yScale = y / imagcanvasref.value.clientHeight

  setFieldsValue({ x: xScale, y: yScale })

  // 更新图标位置
  iconPosition.value = { x: xScale, y: yScale };
  // 获取上下文
  const context = canvas.value.getContext('2d');
  if (!context) return;
  // 清除旧的图标
  clearOldIcon(context);
  if (iconImage.value.src) return;
  drawImagIcon(context)
};

/**
 *
 * @param context 清除上次点击的图标
 * 注意，这里需要先重新绘制背景图片，然后加载定位图标
 */
const clearOldIcon = (context: CanvasRenderingContext2D) => {
  // 清除canvas
  // 如果有保存的图标坐标，先清除旧的图标
  if (iconPosition.value && iconImage.value.src.length !== 0) {
    clearContext()
    const image = new Image();
    image.src = currentIMG.value; // 设置你的图片路径
    image.onload = () => {
      context?.drawImage(image, 0, 0, originWH.width, originWH.height);
    };
    drawImagIcon(context)
  }
};

/**
 * 
 * @param ctx 绘制定位图标
 */
const drawImagIcon = (ctx) => {
  iconImage.value.src = location; // 设置你的图片路径
  const xReal = iconPosition.value?.x * imagcanvasref.value.clientWidth;
  const yReal = iconPosition.value?.y * imagcanvasref.value.clientHeight;
  iconImage.value.onload = () => {
    ctx.drawImage(iconImage.value, xReal - iconImage.value.width / 2, yReal - iconImage.value.height / 2);
  };
}

// 加载IMG
async function reloadIMG(senceId, isFirst?: boolean, frame: any = null) {
  const ret = await fileDownload({ id: senceId, isOnline: true })
  const blob = new Blob([ret])
  const reader = new window.FileReader();
  reader.readAsDataURL(blob)
  reader.onloadend = function () {
    currentIMG.value = reader.result
    // if (frame.frame) {
    //   imageSize.value = { width: frame.frame.width, height: frame.frame.height }
    // }
    drawBackground(currentIMG.value, isFirst)
  }
}

// 有canvas绘制背景图
const drawBackground = (url, isFirst = false) => {
  const context = canvas.value?.getContext('2d');
  const width = document.getElementById('rightcard')?.offsetWidth || 0
  const height = document.getElementById('rightcard')?.offsetHeight || 0
  canvas.value?.setAttribute('width', `${width}`)
  canvas.value?.setAttribute('height', `${height}`)

  if (!context) return;

  const image = new Image();
  image.src = url; // 设置你的图片路径
  image.onload = () => {
    context.clearRect(0, 0, width, height);
    context?.drawImage(image, 0, 0, width, height);
    isFirst && initialIcon()
  };
};

// 图标的初始化
const initialIcon = () => {
  originWH = {
    width: document.getElementById('rightcard')?.offsetWidth || 0,
    height: document.getElementById('rightcard')?.offsetHeight || 0
  }
  if (!canvas.value || !canvas.value.getContext) return;
  // 获取上下文
  const context = canvas.value.getContext('2d');
  if (!context) return;
  iconImage.value.src = location; // 设置你的图片路径
  const xReal = iconPosition.value?.x * imagcanvasref.value.clientWidth;
  const yReal = iconPosition.value?.y * imagcanvasref.value.offsetHeight;
  iconImage.value.onload = () => {
    context.drawImage(iconImage.value, xReal - iconImage.value.width / 2, yReal - iconImage.value.height / 2);
  };
};

async function handleSubmit() {
  const values = await validate()
  const params = {
    ...values,
    id: recordRef.value.data.id,
    code: recordRef.value.data.code,
    name: recordRef.value.data.name,
    type: recordRef.value.data.type.code,
    sceneId: currentSenceId.value,
    coordinate: {
      x: values.x,
      y: values.y,
      z: 0,
    },
  }
  // console.log('values', params);
  updateDevice(params).then(res => {
    closeDrawer()
    clearContext();
    emit('success')
  })
}

const clearContext = () => {
  if (!canvas.value || !canvas.value.getContext) return;
  // 清除canvas
  const context = canvas.value?.getContext('2d');
  context && context.clearRect(0, 0, canvas.value?.width, canvas.value?.height);
};

onMounted(() => {
  // fetch();
  drawBackground(defaultScence)
});

onUnmounted(() => {
  clearContext();
});

</script>

<style lang="less" scoped>
.rightcard {
  width: 100%;
  height: 100%;
  background-color: rgb(243 245 248);

  .image-annotation {
    width: 100%;
    height: 100%;
  }
}
</style>
